package com.my.user.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.Properties;

public class DataSourceUtils {
    public static DataSource getDataSourceWithC3P0(){
        ComboPooledDataSource c3p0 = new ComboPooledDataSource();
        try {
            c3p0.setDriverClass("com.mysql.jdbc.Driver");
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        c3p0.setJdbcUrl("jdbc:mysql://localhost:3306/jsppro");
        c3p0.setUser("root");
        c3p0.setPassword("12345678");
        return c3p0;
    }

    public static DataSource getDataSourceWithC3P0ByXML(){
        ComboPooledDataSource c3p0 = new ComboPooledDataSource("users");
        return c3p0;
    }

    public static DataSource getDataSourceWithDBCP(){
        BasicDataSource dbcp = new BasicDataSource();
        dbcp.setDriverClassName("com.mysql.jdbc.Driver");//设置连接数据库的驱动名
        dbcp.setUrl("jdbc:mysql://localhost:3306/jsppro");//设置连接数据库的URL
        dbcp.setUsername("root");//设置数据库的用户名
        dbcp.setPassword("12345678");//设置数据库的密码
        dbcp.setInitialSize(20);//设置初始化时，连接池中的连接数量
        dbcp.setMaxActive(10);//设置连接池中，处于活动状态的数据库连接的最大数量
        dbcp.setMaxIdle(10);//设置连接池中，处于空闲状态的数据库连接的最大数量
        return dbcp;
    }

    public static DataSource getDataSourceWithDBCPByProperties() throws Exception{
        DataSource dbcp = null;
        Properties props = new Properties();
        InputStream input = new DBCPDemo().getClass().getClassLoader().getResourceAsStream("dbcpconfig.properties");
        props.load(input);
        dbcp = BasicDataSourceFactory.createDataSource(props);
        return dbcp;
    }
}
